const { getEngine } = require("./engine");

const defaultIcon =
  "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/mirror-assets/168e0858b6ccfd57fe5~tplv-t2oaga2asx-no-mark:100:100:100:100.awebp";

class BarkSender {
  constructor(token) {
    this.token = token;
  }

  createUrl(token, text, params = {}) {
    const extraParams = Object.keys(params).reduce(
      (acc, key) =>
        acc === "" ? `?${key}=${params[key]}` : `&${key}=${params[key]}`,
      ""
    );
    return `https://api.day.app/${token}/${encodeURIComponent(
      text
    )}${extraParams}`;
  }

  send(text, params = {}) {
    if (!params.icon) {
      params.icon = defaultIcon;
    }
    return getEngine()(this.createUrl(this.token, text, params), {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      data: params,
    });
  }
}

class BarkPusher {
  constructor() {
    this.tokenByKey = new Map();
  }
  add(key, url) {
    this.tokenByKey.set(key, url);
  }

  use(key) {
    const token = this.tokenByKey.has(key) ? this.tokenByKey.get(key) : key;

    return new BarkSender(token);
  }
}
const bark = new BarkPusher();

module.exports = bark;
